use crate::models::category_translations::{self, CreateParams};
use axum::{
    Json, Router,
    extract::State,
    routing::{get, post},
};
use loco_rs::prelude::*;

pub fn routes() -> Router<AppContext> {
    Router::new()
        .route("/category-translations", post(create))
        .route("/category-translations/:id", get(get_by_id))
        .route("/category-translations/:id/delete", post(delete))
        .route(
            "/category-translations/by-category/:category_id",
            get(get_by_category),
        )
        .route(
            "/category-translations/by-locale/:category_id/:locale",
            get(get_by_locale),
        )
}

async fn create(
    State(state): State<AppContext>,
    Json(params): Json<CreateParams>,
) -> Result<Response> {
    let translation = category_translations::Model::create(&state.db, &params).await?;
    format::json(translation)
}

async fn get_by_id(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Result<Response> {
    let translation = category_translations::Model::find_by_id(&state.db, &id).await?;
    format::json(translation)
}

async fn delete(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Result<Response> {
    let translation = category_translations::Model::find_by_id(&state.db, &id).await?;
    translation.delete(&state.db).await?;
    format::json(())
}

async fn get_by_category(
    State(state): State<AppContext>,
    axum::extract::Path(category_id): axum::extract::Path<String>,
) -> Result<Response> {
    let translations =
        category_translations::Model::find_by_category_id(&state.db, &category_id).await?;
    format::json(translations)
}

async fn get_by_locale(
    State(state): State<AppContext>,
    axum::extract::Path((category_id, locale)): axum::extract::Path<(String, String)>,
) -> Result<Response> {
    let translation =
        category_translations::Model::find_by_category_and_locale(&state.db, &category_id, &locale)
            .await?;
    format::json(translation)
}
